import { toast as showToast } from "@/BtComponents/BtToast/store"
import { useTokenStore } from '@/stores/useTokenStore';
import Taro from '@tarojs/taro'

/**
 * @description: page init 静默登录后执行业务逻辑
 * @return {*}
 */
const initPage = () => {
  return new Promise(resolve => {
    setTimeout(() => {
      const token = useTokenStore.getState().token
      if (token) {
        resolve(token)
      } else {
        useTokenStore.subscribe(state => {
          if (state.token) {
            // 解决toke请求header没有携带上
            resolve(token)
          }
        })
      }
    }, 100)
  })
}

/**
 * @description: toast 消息
 * @param {string} text
 * @param {string} icon
 * @return {*}
 */
const toast = (text: string, icon?: string) => {
  showToast(text, icon)
}

/**
 * @description: 显示/隐藏loading
 * @param {boolean} show - 是否显示loading
 * @param {string} title - loading提示文字
 * @return {*}
 */
const loading = (show: boolean, title = '加载中...') => {
  if (show) {
    Taro.showLoading({
      title,
      mask: true
    })
  } else {
    Taro.hideLoading()
  }
}

export default {
  initPage,
  toast,
  loading
}
